package rmiServeur;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Lanceur_Serveur {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length != 2) {
			System.err.println("Usage : java server <server External ip or name> <port number>");
			System.exit(1);
		}

		int port = 0;
		try {
			port = Integer.parseInt(args[1]);
		} catch (NumberFormatException e) {
			System.err
					.println("The <port number> argument has to be in a decimal numeric format");
			System.exit(2);
		}

		Serveur_IMPL s = null;
		try {
			s = new Serveur_IMPL();
		} catch (RemoteException e1) {
			System.err
					.println("An error occured during the creation of the instance of server");
			System.exit(3);
		}

		Registry registry = null;

		try {
			registry = LocateRegistry.createRegistry(port);
		} catch (NumberFormatException e1) {
			System.err
					.println("The format of the port number is not correct but this exception has already be checked");
			System.exit(2);
		} catch (RemoteException e1) {
			System.err.println("The registry cannot be created");
			System.exit(7);
		}

		try {
			//registry.rebind(//) doesn't Always work on external port
			//we will use Namming.rebind(...)
			//registry.rebind("server", s);
			Naming.rebind("rmi://"+args[0]+":"+port+"/server", s);
			System.out.println("Server ready");

		} catch (RemoteException e) {
			System.err.println("A remote error occurs localy");
			System.exit(5);
		} catch (MalformedURLException e) {
			System.err.println("the ip or server name is invalid");
			System.exit(6);
		}

	}
}
